package com.secsbrain.deploy.utils.command;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

/**
 * Created by yangyang.zhang on 2017/7/10.
 */
public class ParseYamlStrategy<T> extends ExecuteStrategyAdapter {
	
	private static final Logger logger = LoggerFactory.getLogger(ParseYamlStrategy.class);

    private StringBuilder yamlString = new StringBuilder();
    private Class<T> resultClazz;
    private T result;
    
    private static final String LINE_SEPARATOR = "----------";
    private static final String SPECIAL_CHAR = "0,0,0,0,0,0";
    private static final String NOT_CONNECTED = "Minion did not return. [Not connected]";

    public ParseYamlStrategy(Class<T> resultClazz) {
        this.resultClazz = resultClazz;
    }

    @Override
    public void processLine(String line) {

    	if (StringUtils.containsAny(line, LINE_SEPARATOR)||
                StringUtils.containsAny(line, NOT_CONNECTED)||
                StringUtils.containsAny(line, SPECIAL_CHAR)) {
            return;
        }
        yamlString.append(line);
        yamlString.append(System.lineSeparator());
    }

    @Override
    public void handleException(Exception e) {

    }

    @Override
    public void handleResult(Object result) {
        Yaml yaml = new Yaml();
        logger.debug(yamlString.toString());
        this.result = yaml.loadAs(yamlString.toString(), resultClazz);
    }

    public T getResult() {
        return result;
    }
}
